<template>
  <!-- 公共底部组件 -->
  <footer>
    <ul>
      <li
        v-for="(item, index) in tabbarList"
        :key="index"
        :class="{ active: active === index }"
        @click="tabbarClick(index, item.url)"
      >
        <img v-if="active == index" :src="item.imgClick" alt="item.title" />
        <img v-else :src="item.imgUrl" alt="item.title" />
        <p>{{ item.title }}</p>
      </li>
    </ul>
  </footer>
</template>

<script>
export default {
  data() {
    return {
      tabbarList: [
        {
          imgUrl: require("../../assets/images/index.png"),
          imgClick: require("../../assets/images/index_click.png"),
          title: "首页",
          url: "/home/index",
        },
        {
          imgUrl: require("../../assets/images/chat.png"),
          imgClick: require("../../assets/images/chat_click.png"),
          title: "聊",
          url: "/home/chat",
        },
        {
          imgUrl: require("../../assets/images/customize.png"),
          imgClick: require("../../assets/images/customize_click.png"),
          title: "定制",
          url: "/home/customize",
        },
        {
          imgUrl: require("../../assets/images/mine.png"),
          imgClick: require("../../assets/images/mine_click.png"),
          title: "我的",
          url: "/home/mine",
        },
      ],
      active: +sessionStorage.getItem("active") || 0,
    };
  },
  methods: {
    tabbarClick(i, url) {
      // 改变样式的
      this.active = i;
      // 用到了本地存储，本地存储是不会被刷新掉的
      sessionStorage.setItem("active", this.active);
      // 切换路由
      this.$router.push(url);
    },
  },

  watch: {
    $route(to) {
      this.tabbarList.forEach((item, index) => {
        // if (to.path === item.url) {
        //   this.active = index;
        // }
        if (to.path.startsWith(item.url)) {
          this.active = index;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100px;
  background: #fff;

  ul {
    display: flex;
    justify-content: space-between;
    height: 100%;

    li {
      flex: 1;
      height: 100%;
      padding: 10px 0;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      font-size: 24px;
      color: #8c8c8c;

      p {
        margin-top: 5px;
      }
    }

    li:nth-child(1) img {
      width: 51px;
      height: 48px;
    }

    li:nth-child(2) img {
      width: 49px;
      height: 37px;
    }

    li:nth-child(3) img {
      width: 48px;
      height: 50px;
    }

    li:nth-child(4) img {
      width: 35px;
      height: 50px;
    }

    .active {
      color: #000;
    }
  }
}
</style>
